package com.dc.util;

import com.dc.exceptions.BizException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;

import java.io.*;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;

/**
 * 新增数据源工具类
 */

public class ScriptRunnerExecSql {

    public static String addSource(String host, String userName, String userPassword, String Port, String content) {
        File file = null;
        try {
            Connection conn = getMySqlConnection(host, userName, userPassword, Port);
            ScriptRunner runner = new ScriptRunner(conn);
            Resources.setCharset(Charset.forName("UTF-8")); //设置字符集,不然中文乱码插入错误
            runner.setLogWriter(null);//设置是否输出日志
            // 绝对路径读取
            String filename = "basic_data.sql";

            file = new File(filename);
            //如果文件不存在  就创建一个空的文件
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //3.写入数据
            //创建文件字节输出流
            FileOutputStream fos = new FileOutputStream(filename);
            //开始写
            String str = content;
            byte[] bytes = str.getBytes();
            //将byte数组中的所有数据全部写入
            fos.write(bytes);
            //关闭流
            fos.close();
//            File file = new File("E:\\work\\dc-control-service\\basic_data.sql");
            Reader read = new FileReader(file);
//            // 从class目录下直接读取
//            Reader read = Resources.getResourceAsReader(content);
            runner.runScript(read);
            runner.closeConnection();
            conn.close();
            read.close();
            System.out.println("sql脚本执行完毕");
            file.delete();
            return "200";
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("sql脚本执行发生异常");
        }
    }

    /**
     * @return
     * @throws Exception
     * @功能描述： 获取数据库连接
     */
    public static Connection getMySqlConnection(String host, String userName, String userPassword, String Port) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://" + host + ":" + Port + "/" + "" + "?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=true&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
        return DriverManager.getConnection(url, userName, userPassword);
    }


}